package com.tb.boxman;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
import android.view.MotionEvent;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;

/**
 * Created by 汪贵春 on 2016/7/11.
 */
public class Gaming {

    public static boolean cheatMode = false;

    //边距
    public static final int PADDING_X = 20;
    public static final int PADDING_Y = 20;
    
    //定位变量
    public static SharedPreferences sp;     //存档
    public static int round;
    public static int sumOfRound;
    public static int cellSize ;
    public static int column;
    public static int row;
    public static int targets;
    public static int startX;
    public static int startY;
    public static boolean notMove;

    public static boolean roundPass;

    private boolean isPressedCheat;
    private boolean isPressedAgain;
    private boolean isPressedBack;
    private boolean isPressedForward;


    //记录手势按下坐标
    private float x1 = 0;
    private float y1 = 0;

    //地图数组
    private int[][] map;

    //玩家坐标
    int[] player;

    //目标点
    int[][] target;

    //图片资源
    private Bitmap boxImage;
    private Bitmap boxImageRight;
    private Bitmap wallImage;
    private Bitmap targetImage;
    private Bitmap playerImage;
    private Bitmap princessImage;
//    private Bitmap doorImage;
    private Bitmap cheatModeImage;
    private Bitmap normalModeImage;
    private Bitmap forwardImage;
    private Bitmap backImage;
    private Bitmap refreshImage;
    

    //地图集
    private Maps maps;


    private void loadMap(int round){
        notMove = true;
        map = maps.getMap(round);
        player = maps.getPlayer(round);
        target = maps.getTarget(round);
    }


    public Gaming(){
        maps = new Maps();
        sumOfRound = maps.getSumOfMaps();

        sp = MainActivity.main.getSharedPreferences("save", Context.MODE_PRIVATE);
        //读档
        round = sp.getInt("round",0);

        //加载图片资源
        Resources res = MainActivity.main.getResources();
        boxImage = BitmapFactory.decodeResource(res, R.drawable.box);
        boxImageRight = BitmapFactory.decodeResource(res, R.drawable.box_right);
        wallImage = BitmapFactory.decodeResource(res, R.drawable.wall);
        targetImage = BitmapFactory.decodeResource(res, R.drawable.target);
        playerImage = BitmapFactory.decodeResource(res, R.drawable.player);
        princessImage = BitmapFactory.decodeResource(res,R.drawable.princess);
//        doorImage = BitmapFactory.decodeResource(res, R.drawable.door);
        refreshImage = BitmapFactory.decodeResource(res,R.drawable.again);
        cheatModeImage = BitmapFactory.decodeResource(res,R.drawable.cheat);
        normalModeImage = BitmapFactory.decodeResource(res,R.drawable.not_cheat);
        forwardImage = BitmapFactory.decodeResource(res,R.drawable.forward);
        backImage = BitmapFactory.decodeResource(res,R.drawable.back);
    }


    public void draw(Canvas canvas, Paint paint){

        if(roundPass){
            loadMap(round);
            roundPass = false;
        }

        //计算各定位变量
        targets = target.length;
        column = map[0].length;
        row = map.length;
        cellSize = Math.min(GameView.screenW - 2 * PADDING_X, GameView.screenH - 2 * PADDING_Y) / Math.max(column, row);
        startX = (GameView.screenW - cellSize * column) / 2;
        startY = (GameView.screenH - cellSize * row) / 2;


        //绘图用起点和终点矩形
        RectF rectF = new RectF();
        //目标点
        if (round == sumOfRound - 1) {
            //最后一关
            float x   = startX + target[0][1] * cellSize;
            float y   = startY + target[0][0] * cellSize;
            rectF.set(x, y, x + cellSize, y + cellSize);
            canvas.drawBitmap(princessImage, null, rectF, paint);
        } else {
            for (int i = 0; i < targets; i++) {
                float x   = startX + target[i][1] * cellSize;
                float y   = startY + target[i][0] * cellSize;
                rectF.set(x, y, x + cellSize, y + cellSize);
                canvas.drawBitmap(targetImage, null, rectF, paint);
            }
        }

        //墙壁和Box
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                float x   = startX + j * cellSize;
                float y   = startY + i * cellSize;
                rectF.set(x, y, x + cellSize, y + cellSize);
                switch (map[i][j]) {
                    case 0:
                        break;
                    case 1:
                        canvas.drawBitmap(wallImage, null, rectF, paint);
                        break;
                    case 2:
                        for (int k = 0; k < targets; k++) {
                            int m = target[k][0];
                            int n = target[k][1];
                            if (i == m && j == n) {
                                canvas.drawBitmap(boxImageRight, null, rectF, paint);
                                break;
                            } else {
                                canvas.drawBitmap(boxImage, null, rectF, paint);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

//        //door
//        float x = startX + maps.getPlayer(round)[1] * cellSize;
//        float y = startY + maps.getPlayer(round)[0] * cellSize;
//        rectF.set(x, y, x + cellSize, y + cellSize);
//        canvas.drawBitmap(doorImage, null, rectF, paint);

        //player
        float x   = startX + player[1] * cellSize;
        float y   = startY + player[0] * cellSize;
        rectF.set(x, y, x + cellSize, y + cellSize);
        canvas.drawBitmap(playerImage, null, rectF, paint);




        //按键
        x = PADDING_X;
        y = PADDING_Y;
        rectF.set(x,y,x + cellSize,y + cellSize);
        if(isPressedCheat){
            paint.setARGB(100,0,0,0);
            canvas.drawRect(rectF,paint);
            paint.setAlpha(255);
        }
        if(cheatMode){
            canvas.drawBitmap(cheatModeImage, null, rectF, paint);
        }else{
            canvas.drawBitmap(normalModeImage, null, rectF, paint);
        }

        x = GameView.screenW - PADDING_X - cellSize;
        y = PADDING_Y;
        rectF.set(x,y,x + cellSize,y + cellSize);
        if(isPressedAgain){
            paint.setARGB(100,0,0,0);
            canvas.drawRect(rectF,paint);
            paint.setAlpha(255);
        }
        canvas.drawBitmap(refreshImage, null, rectF, paint);


        if(cheatMode){
            x = PADDING_X;
            y = GameView.screenH / 2 - cellSize;
            rectF.set(x,y,x + cellSize,y + 2 * cellSize);
            if(isPressedBack){
                paint.setARGB(100,0,0,0);
                canvas.drawRect(rectF,paint);
                paint.setAlpha(255);
            }
            canvas.drawBitmap(backImage, null, rectF, paint);

            x = GameView.screenW - PADDING_X - cellSize;
            y = GameView.screenH / 2 - cellSize;
            rectF.set(x,y,x + cellSize,y + 2 * cellSize);
            if(isPressedForward){
                paint.setARGB(100,0,0,0);
                canvas.drawRect(rectF,paint);
                paint.setAlpha(255);
            }
            canvas.drawBitmap(forwardImage, null, rectF, paint);
        }

        //关卡指示器
        paint.setTextSize(100);
        paint.setColor(Color.BLUE);
        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText(round + 1 + "/" + sumOfRound,GameView.screenW / 2, cellSize,paint);

        //cheatMode指示器
        if(cheatMode){
            paint.setTextSize(50);
            paint.setColor(Color.BLUE);
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("Cheat Mode",GameView.screenW / 4, cellSize,paint);
        }





    }


    public void onTouchEvent(MotionEvent event){

        float touchX = event.getX();
        float touchY = event.getY();

        //按键识别
        float x = PADDING_X;
        float y = PADDING_Y;
        if (touchX > x && touchX < x + cellSize &&
                touchY > y && touchY < y + cellSize) {
            isPressedCheat = true;
        }else{
            isPressedCheat = false;
        }

        x = GameView.screenW - PADDING_X - cellSize;
        y = PADDING_Y;
        if (touchX > x && touchX < x + cellSize &&
                touchY > y && touchY < y + cellSize) {
            isPressedAgain = true;
        }else{
            isPressedAgain = false;
        }

        x = PADDING_X;
        y = GameView.screenH / 2 - cellSize;
        if (touchX > x && touchX < x + cellSize &&
                touchY > y && touchY < y + 2 * cellSize) {
            isPressedBack = true;
        }else{
            isPressedBack = false;
        }

        x = GameView.screenW - PADDING_X - cellSize;
        y = GameView.screenH / 2 - cellSize;
        if (touchX > x && touchX < x + cellSize &&
                touchY > y && touchY < y + 2 * cellSize) {
            isPressedForward = true;
        }else{
            isPressedForward = false;
        }







        //滑动手势识别
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            //当手指按下的时候
            x1 = event.getX();
            y1 = event.getY();
        }
        if(event.getAction() == MotionEvent.ACTION_UP) {
            //当手指离开的时候
            float x2 = event.getX();
            float y2 = event.getY();
//            Log.d("tb",x1 + " , " + y1);
//            Log.d("tb",x2 + " , " + y2);
            int direction = 0;
            if(y1 - y2 > 50 && y1 - y2 > Math.abs(x1 - x2)) {
                direction = 1;
                Log.d("tb",  "向上滑");
            } else if(y2 - y1 > 50 && y2 - y1 > Math.abs(x2 - x1)) {
                direction = 2;
                Log.d("tb", "向下滑");
            } else if(x1 - x2 > 50 && x1 - x2 > Math.abs(y2 - y1)) {
                direction = 3;
                Log.d("tb", "向左滑");
            } else if(x2 - x1 > 50 &&  x2 - x1 > Math.abs(y2 - y1)) {
                direction = 4;
                Log.d("tb",  "向右滑");
            }
            moveAction(direction);

            buttonAction();

        }

    }

    private void buttonAction() {
        if(isPressedCheat){
            cheatMode = !cheatMode;
        }
        if(isPressedAgain){
            runAnimation();
            loadMap(round);
        }
        if(cheatMode){
            if(isPressedBack){
                if(round != 0 )
                    round--;
                runAnimation();
                loadMap(round);
            }
            if(isPressedForward){
                if(round != sumOfRound-1)
                    round++;
                runAnimation();
                loadMap(round);
            }
        }
        isPressedCheat = isPressedAgain = isPressedForward = isPressedBack = false;
    }

    public void onBackKeyUp(){
        if(notMove){
            GameView.gameState = GameView.GAME_MENU;
        }else{
            runAnimation();
            loadMap(round);
        }

        GameView.main.invalidate();
    }


    //滑动动作
    private void moveAction(int direction) {
        int m = player[1];      //记录玩家下一步x
        int n = player[0];      //记录玩家下一步y
        int p = player[1];      //记录下一步面前的x
        int q = player[0];      //记录下一步面前的y

        switch (direction) {
            case 1:
                n -= 1;
                q -= 2;
                break;
            case 2:
                n += 1;
                q += 2;
                break;
            case 3:
                m -= 1;
                p -= 2;
                break;
            case 4:
                m += 1;
                p += 2;
                break;
            default:
                break;
        }

        //移动处理
        if (m < column && n < row && n >= 0 && m >= 0) {      //未出界

            if (map[n][m] == 1) {
                //...碰墙
                if (cheatMode) {
                    notMove = false;
                    player[0] = n;
                    player[1] = m;
                }
            } else if (map[n][m] == 2) {
                //箱子
                if (map[q][p] == 0) {
                    notMove = false;
                    //移动人物
                    player[0] = n;
                    player[1] = m;
                    //移动箱子
                    map[q][p] = 2;
                    map[n][m] = 0;
                }
            } else {
                //空地
                notMove = false;
                player[0] = n;
                player[1] = m;
            }
        }


        //之前未通关才需判断
        if (!roundPass) {
            roundPass = true;

            if (round == sumOfRound - 1) {
                if (player[0] != target[0][0] || player[1] != target[0][1]) {
                    roundPass = false;
                }
            } else {
                for (int i = 0; i < targets; i++) {
                    m = target[i][0];
                    n = target[i][1];
                    if (map[m][n] != 2) {
                        roundPass = false;
                    }
                }
            }
            //现在通关
            if (roundPass) {
                round++;
                if (round == sumOfRound) {
                    round = 0;
                    GameView.gameState = GameView.GAME_WIN;
                }
                //存档
                sp.edit().putInt("round",round).apply();
                runAnimation();

            }

        }
    }


    private void runAnimation(){
        AlphaAnimation     alphaAnimation  = new AlphaAnimation(0.8f, 0);
        RotateAnimation    rotateAnimation = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ScaleAnimation     scaleAnimation  = new ScaleAnimation(1, 0, 1, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        final AnimationSet animationSet    = new AnimationSet(true);
        animationSet.addAnimation(alphaAnimation);
        animationSet.addAnimation(rotateAnimation);
        animationSet.addAnimation(scaleAnimation);
        animationSet.setDuration(500);

        AlphaAnimation     alphaAnimation2  = new AlphaAnimation(0, 1);
        RotateAnimation    rotateAnimation2 = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ScaleAnimation     scaleAnimation2  = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        final AnimationSet animationSet2    = new AnimationSet(true);
        animationSet2.addAnimation(alphaAnimation2);
        animationSet2.addAnimation(rotateAnimation2);
        animationSet2.addAnimation(scaleAnimation2);
        animationSet2.setDuration(1000);

        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                GameView.main.startAnimation(animationSet2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        GameView.main.startAnimation(animationSet);
    }





}
